<script setup>
import { onMounted, onUnmounted, ref, watch } from 'vue'
//  按需引入 echarts
import * as echarts from 'echarts/core'
import 'echarts-gl'
import { sleep } from '@/utils/sleep'
import DaTong from '@/assets/geojson/平城区.json'

const main = ref() // 使用ref创建虚拟DOM引用，使用时用main.value
let myChart = echarts.ECharts

// 接收父组件传递的参数
const props = defineProps({
  option: {
    type: Object,
    default: null
  },
  height: {
    type: String,
    default: '100%'
  },
  sleepTime: {
    type: Number,
    default: 1000
  },
  style: {
    type: Object,
    default: () => ({})
  }
})
const optionData = ref(props.option)
const height = ref(props.height)
const sleepTime = ref(props.sleepTime)
const style = ref(props.style)
// optionData 为响应式数据，当父组件传递的option改变时，更新optionData
watch(
  () => props.option,
  (val) => {
    optionData.value = val
    if (myChart) {
      myChart.setOption(optionData.value)
    }
  },
  {
    deep: true
  }
)

const init = async () => {
  await sleep(sleepTime.value)
  // 基于准备好的dom，初始化echarts实例
  echarts.registerMap('DaTong', DaTong, {});
  myChart = echarts.init(main.value)
  myChart?.setOption(optionData.value)
}
onMounted(() => {
  init().then(() => {
    window.addEventListener('resize', myChart?.resize)
  })
})
onUnmounted(() => {
  window.removeEventListener('resize', myChart?.resize)
})
</script>

<template>
  <div ref="main" :style="{
    width: '100%',
    height: height,
    ...style
  }"></div>
</template>

<style scoped></style>
